<?php

class Set implements XMLConvertable, JSONConvertable {

	protected $elements;
	protected $typifed;
	protected $index;
	protected $name;

	function __construct($init = null, $typifed = false) {
		$this->elements = $init;
		reset($this->elements);
		$this->typifed = $typifed;
		$this->index = 0;
	}

	function read_array() {
		return $this->elements;
	}

	function __get($name) {
		if ($this->typifed && !key_exists($name, $this->elements)) throw new Exception("Field `$name` not defined!");
		return @$this->elements[$name];
	}

	function __set($name, $val) {
		if ($this->typifed && !key_exists($name, $this->elements)) throw "Field `$name` not defined!";
		$this->elements[$name] = $val;
	}

	function iterate($f) {
		foreach ($this->elements as $k=>$v) {
			$f($k, $v);
		}
	}

	/**
	 * возвращает следующий элемент списка
	 *
	 * @return mixed
	 */
	function next() {
		return next($this->elements);
	}

	function prev() {
		return prev($this->elements);
	}

	function curn () {
		$ret = $this->current();
		$this->next();
		return $ret;
	}

	function current() {
		return current($this->elements);
	}

	function key() {
		return key($this->elements);
	}

	function reset() {
		reset($this->elements);
	}

	function count() {
		return count($this->elements);
	}

	function toXML(SimpleXMLElement &$parent = NULL) {
		if (!$parent) $xml = simplexml_load_string('<set/>');
		else {
			$xml = $parent->addChild('set');
		}
		foreach ($this->elements as $key=>$elem)
		{
			if (is_a($elem, 'XMLConvertable')) {
				$elem->toXML($xml);
			} elseif (is_string($key)) {
                            $xml->$key = $elem.'';
                        } else {
                            $xml->element[$key] =  $elem;
                            $xml->element[$key]['id'] = $key;
                        }
		}
		return $xml;
	}

	function name($nn = NULL)
	{
		$ret = $this->name;
		if ($nn != NULL) $this->name = $nn;
		return $ret;
	}

	function toJSON() {
		$res = json_encode($this->elements);
		return $res;
	}
}
?>